<template>
  <!--可见光人脸管理-->
  <div class="components-layout-demo">
    <a-layout style="height:100%">
      <a-layout style="background: #fff;height:100%">
        <a-layout-sider class="layout-sider-left">
          <div style="height:100%;">
            <sidebar-check-user
              :deptTree="deptTree"
              :deptChecked.sync="deptCheckedLeft"
              :userChecked.sync="userCheckedLeft"
              :userSerialChecked.sync="userSerialCheckedLeft"
              @on-check="serchByChecked"
              @on-select="serchByselected"
              :heightTree ='heightTreeLeft'
              :heightTable ="heightTableLeft"
              :setHeight="'13px'"
            />
          </div>
        </a-layout-sider>
        <a-layout-content class="layoutContent">
          <div class="components-table-demo-size" style="height:100%">
            <!-- tools盒子 每个页面必须存在的div盒子，除了表格以外的功能都放在这个里面 -->
            <div id="tools">
              <div class="height8"></div>

              <a-form layout="inline" style="text-align: left;padding: 0 10px;" :selfUpdate="true">
                <!--<a-form-item label="开始日期" class="marginBtm">-->
                  <!--<a-date-picker-->
                    <!--:disabledDate="disabledStartDate"-->
                    <!--format="YYYY-MM-DD"-->
                    <!--v-model="startDate"-->
                    <!--placeholder="开始日期"-->
                    <!--style="width: 150px;"-->
                    <!--@openChange="handleStartOpenChange"-->
                  <!--/>-->
                <!--</a-form-item>-->
                <!--<a-form-item label="结束日期" class="marginBtm">-->
                  <!--<a-date-picker-->
                    <!--:disabledDate="disabledEndDate"-->
                    <!--format="YYYY-MM-DD"-->
                    <!--placeholder="结束日期"-->
                    <!--v-model="endDate"-->
                    <!--:open="endOpen"-->
                    <!--style="width: 150px;"-->
                    <!--@openChange="handleEndOpenChange"-->
                  <!--/>-->
                <!--</a-form-item>-->
                <a-form-item label="录入状态" class="marginBtm">
                  <a-select
                    v-model="defaultRecordType"
                    showArrow
                    placeholder="请选择录入状态"
                    style="width: 200px;"
                    @change="handleChange"
                    @popupScroll="popupScroll"
                  >
                    <a-select-option
                      v-for="bdRecordType in bdRecordTypeList"
                      :key="bdRecordType.recordType"
                    >{{bdRecordType.recordTypeName}}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="关键字" class="marginBtm">
                  <a-input v-model="searchNameRight"
                           allowClear placeholder="请输入工号/姓名" class="marginBtm"
                           @pressEnter="handleQuery"/>
                </a-form-item>

                <a-form-item class="marginBtm">
                  <a-button type="primary" @click="handleQuery">
                    查询
                  </a-button>
                </a-form-item>
              </a-form>

              <a-divider style="margin: 5px 0"/>

              <!-- 功能按钮 -->
              <div class="divPadiAlign">
                <a-button type="primary" class="button-marin" @click="visibleImport = true">
                  人脸照片导入
                </a-button>
                <a-button type="primary" class="button-marin" @click="faceDeletion">
                  人脸照片删除
                </a-button>
                <a-button type="primary" class="button-marin" @click="handleExport">
                  导出
                </a-button>
              </div>

            </div>
            <!-- 右侧数据表格 -->
            <div id="tableBox" class="tableOthStyle">
              <a-table
                bordered
                class="a-table"
                size="small"
                :columns="columnsRight"
                :dataSource="listRight"
                :loading="tableLoading"
                :rowKey="(record) => record.userSerial"
                :pagination="paginationRight"
                :scroll="{ y: yHeight,x: xWidth}"
                :customRow="clickRow"
                :rowSelection="{selectedRowKeys:selectedXhRight,fixed:true,onChange:onChangeRight}"
              />
            </div>
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>

    <!--人脸照片导入-->
    <a-modal
      width="700px"
      title="照片导入"
      :visible="visibleImport"
      @ok="handleOkImport"
      :confirmLoading="confirmLoading"
      @cancel="handleCancelImport"
      :maskClosable="false"
      cancelText="取消"
      okText="导入"
    >
      <a-upload
        :multiple="false"
        :fileList="fileList"
        :remove="handleRemove"
        :beforeUpload="beforeUpload"
      >
        <a-button type="primary" :disabled="unloadDisabled">
          <!--<a-icon type="upload" />-->
          上传文件
        </a-button>
      </a-upload>

      <!--<a-divider style="margin: 20px 0 15px 0;"/>-->
      <!--导入方式：-->
      <!--<a-radio-group v-model="radioValue">-->
        <!--<a-radio :value="1">-->
          <!--照片名与工号对应-->
        <!--</a-radio>-->
        <!--<a-radio :value="2">-->
          <!--照片名与姓名对应-->
        <!--</a-radio>-->
      <!--</a-radio-group>-->
      <a-divider style="margin: 20px 0 15px 0;"/>
      <p style="margin-bottom: 0;color: #ff3664;">1、照片请统一使用jpg格式，每个员工导入1张清晰照片，并以工号命名，打包.zip格式导入！
        <br/>2、工号命名格式：工号.jpg，例如：20112.jpg
        <br/>3、照片的拍摄尽量参照证件照拍摄标准
        <br/>4、导入日志可在日志查询中查看

      </p>

    </a-modal>

    <!--查看人脸照片-->
    <a-modal
      width="400px"
      title="查看人脸照片"
      :visible="visibleImg"
      @cancel="handleCancelImg"
      :footer="null"
    >
      <!--onerror 要使用服务固定地址获取，部署时更改，参考loginVisitors.vue页面底部-->
      <!--http://10.232.84.149:8090/-->
      <img style="width: 100%" :src="lookImg" alt="" onerror="this.src='https://digitalsecurity.oss-cn-hangzhou.aliyuncs.com/visit/static/img/noImg.png';this.onerror=null">

    </a-modal>

    <!--导入成功后展示信息-->
    <a-modal
      width="500px"
      title="导入提示"
      :visible="resultModel"
      @cancel="handleCanResult"
      @ok="handleCanResult"
      cancelText=""
      okText="确定"
    >
      <p>文件导入完成！</p>
      <p>共导入
        <span style="color: #ff3664;">[{{Number(resultMsg.fail + resultMsg.success)}}]</span> 张照片，成功
        <span style="color: #ff3664;">[{{resultMsg.success}}]</span> 张照片，失败
        <span style="color: #ff3664;">[{{resultMsg.fail}}]</span> 张照片！</p>
      <p>详细信息请到 [日志查询] 中查看！</p>
    </a-modal>

    <!--导出加载中-->
    <customLoading :customVisible="spinning"></customLoading>

  </div>
</template>

<script>
  import sidebarCheckDoor from "@/components/accessControlSystem/sidebarCheckDoor.vue";
  import sidebarCheckUser from "@/components/accessControlSystem/sidebarCheckUser.vue";
  import { tableBoxHeight } from "@/api/communal";
  import dept from "@/api/accessControlSystem/dept";
  import place from "@/api/accessControlSystem/place";
  import door from "@/api/accessControlSystem/door";
  import faceManage from "@/api/accessControlSystem/faceManage";
  import cfg from '@/config/config'
  import moment from "moment";
  import axios from 'axios'

  export default {
    components: {
      sidebarCheckDoor,
      sidebarCheckUser
    },

    data() {
      let _this = this;
      return {
        startDate: moment().startOf('month'), //开始日期 条件
        endDate: moment().endOf('month').endOf('month'), //结束日期 条件
        // 人脸照片导入
        uploadAction: cfg.apiUrl + 'api/parkingLot/importLeaves',  // 导入地址
        fileList:[],   // 导入文件列表
        unloadDisabled: false,
        visibleImport: false,  // 导入模态框开关
        confirmLoading: false,  // 点击导入的时候加载中
        radioValue: 1,   // 导入方式
        spinning: false,// 导出时加载中

        visibleImg: false,  // 查看照片弹窗
        lookImg: "",

        resultModel: false,  // 文件导图结果弹窗
        resultMsg: {
          fail: 0,
          success: 0
        },  // 文件导入成功后返回的结果信息

        jlType: [], //记录类型 条件
        defaultRecordType: 99,
        bdRecordTypeList: [
          {recordType:99,recordTypeName:"全部" },
          {recordType:1,recordTypeName:"未录人脸" },
          {recordType:2,recordTypeName:"已录人脸" }
        ], //所有记录类型

        //树形结构
        deptTree: [],
        placeTree: [],

        /* 左侧 */
        heightTreeLeft:"",
        heightTableLeft:"500",
        deptCheckedLeft: [],
        deptselectedLeft:[],
        userCheckedLeft: [],
        userSerialCheckedLeft: [],

        /* 右侧  */
        yHeight: 500,
        xWidth:1200,
        pageNoRight: 1,
        pageSizeRight: 10,
        searchNameRight: "",
        tableLoading: false,
        listRight: [
          // {"ip":"规则1","userName":"张美丽1","userSerial":"0010021",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达东门","faceStatus":"有","userCard":"723896960","id":3938,"userNo":"8811157","jlType":1,"depName":"信息系统部","mc":"规则1","userLx":1},
          // {"ip":"规则1","userName":"张美丽2","userSerial":"0010022",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达西门","faceStatus":"有","userCard":"723896960","id":3941,"userNo":"8811157","jlType":4,"depName":"信息系统部","mc":"规则1","userLx":2},
          // {"ip":"规则1","userName":"张美丽3","userSerial":"0010023",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达南门","faceStatus":"有","userCard":"723896960","id":3940,"userNo":"8811157","jlType":2,"depName":"信息系统部","mc":"规则1","userLx":3},
          // {"ip":"规则1","userName":"张美丽4","userSerial":"0010024",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"有","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
          // {"ip":"规则1","userName":"张美丽5","userSerial":"0010025",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"有","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
          // {"ip":"规则1","userName":"张美丽6","userSerial":"0010026",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"有","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
          // {"ip":"规则1","userName":"张美丽7","userSerial":"0010027",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"无","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
          // {"ip":"规则1","userName":"张美丽8","userSerial":"0010028",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"无","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
          // {"ip":"规则1","userName":"张美丽9","userSerial":"0010031",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"无","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
          // {"ip":"规则1","userName":"张美丽10","userSerial":"0010032",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"无","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
          // {"ip":"规则1","userName":"张美丽11","userSerial":"0010029",fx:"进",jlSj:"2020-12-12 9:00:00",devLb:"1","doorName":"步达北门","faceStatus":"无","userCard":"723896960","id":3939,"userNo":"8811157","jlType":3,"depName":"信息系统部","mc":"规则1","userLx":4},
        ],
        selectedXhRight: [], // 选择的人的bh集合
        selectedDatas: [],// 选择的行数据集合
        columnsRight: [
          {
            title: '序号',     //表头
            dataIndex: 'serialNumber',   //字段名称
            width: '70px',    //设列宽度
            align: 'center',  //居中显示
            className: 'changeBack',   //重置覆盖背景色为浅灰色，否则是白色的
            customRender: (value, row, index) => `${(this.paginationRight.current - 1) * this.paginationRight.pageSize + index + 1}`  //设置动态序号
          },
          {
            title: "工号",
            dataIndex: "userNo",
            align: "center",
            width: "auto",
            className: 'changeBack'
          },
          {
            title: "姓名",
            dataIndex: "userName",
            align: "center",
            width: "auto",
            className: 'changeBack'
          },
          {
            title: "部门名称",
            dataIndex: "depName",
            align: "center",
            width: "auto",
            className: 'changeBack'
          },
          {
            title: "人脸",
            dataIndex: "faceStatus",
            align: "center",
            width: "auto",
            className: 'changeBack'
          }
        ],
        paginationRight: {
          current: 1,
          pageSize: 30, // 默认每页显示数量
          total: 0, //总条数
          showSizeChanger: true, // 显示可改变每页数量
          pageSizeOptions: [ "20", "30", "50"], // 每页数量选项
          showTotal: total => `共 ${total} 条数据`, // 显示总数
          onShowSizeChange: (current, pageSize) => _this.changePage(1, pageSize), // 改变每页数量时更新显示
          onChange: (current, pageSize) => _this.changePage(current, pageSize) //点击页码事件
        },
        loading: true,
        endOpen: false,
      };
    },
    mounted(){
      let _this = this;
      //加载树形结构数据
      dept.getTreeList().then(res => {
        _this.deptTree = res.result;
      });
      place.getTreeList().then(res => {
        _this.placeTree = res.result;
      });

      this.yHeight = tableBoxHeight();
      this.xWidth = this.columnsRight.length*120;
      // 控制表格底部边框保持在底部，而不是在半空中
      let minHeight = document.getElementsByClassName("ant-table");
      minHeight[0].style.minHeight = tableBoxHeight() + 40 + "px";

      // 计算本页面左侧高度传值给组件
      let height = window.innerHeight;
      // 减的数值具体可参考communal.js,左侧树和表格的高度
      this.heightTableLeft = String(height - 225 - 60);
      this.heightTreeLeft = "height:" + (height - 187) + "px";
    },
    methods: {
      /**
       * 右侧方法
       */
      // 分页刷新
      changePage(current, pageSize) {
        this.paginationRight.current = current;
        this.paginationRight.pageSize = pageSize;
        this.getPressUserQueryList();
      },
      serchByChecked(value){
        this.paginationRight.current = 1;
        this.deptCheckedLeft = value;
        this.deptselectedLeft = [];
        this.getPressUserQueryList()

      },
      serchByselected(value){
        this.paginationRight.current = 1;
        this.deptselectedLeft = value;
        this.deptCheckedLeft = [];
        this.getPressUserQueryList()

      },
      //日期控件需要的方法
      disabledStartDate(startDate) {
        const endDate = this.endDate;
        if (!startDate || !endDate) {
          return false;
        }
        return startDate.valueOf() > endDate.valueOf();
      },
      disabledEndDate(endDate) {
        const startDate = this.startDate;
        if (!endDate || !startDate) {
          return false;
        }
        return startDate.valueOf() >= endDate.valueOf();
      },
      handleStartOpenChange(open) {
        if (!open) {
          this.endOpen = true;
        }
      },
      handleEndOpenChange(open) {
        this.endOpen = open;
      },
      //查询有权限员工
      getPressUserQueryList() {
        let _this = this;

        // _this.startDate = moment(_this.startDate).format("YYYY-MM-DD");
        // _this.endDate = moment(_this.endDate).format("YYYY-MM-DD");
        // let newStartDate = _this.startDate.format("YYYY-MM-DD");
        // let newEndDate = _this.endDate.format("YYYY-MM-DD");
        let placeIdArr = [];
        placeIdArr = placeIdArr.concat(_this.deptCheckedLeft);
        placeIdArr = placeIdArr.concat(_this.deptselectedLeft);
        if (placeIdArr.join(',') == '') {
          this.$message.warning('请勾选部门或人员列表')
          return
        }

        this.tableLoading = true;
        faceManage.getUserInfoAboutFace({
            current: _this.paginationRight.current,
            pageSize: _this.paginationRight.pageSize,
            userSerial: _this.userSerialCheckedLeft.join(","),
            deptSerial: placeIdArr.join(","),
            recordType: _this.defaultRecordType,
            searchVal: _this.searchNameRight
          })
          .then(res => {
            // console.log(res)
            if (res.data.success) {
              _this.tableLoading = false;
              _this.selectedXhRight = [];
              _this.paginationRight.total = res.data.result.total;
              _this.listRight = res.data.result.records;
            } else {
              _this.tableLoading = false;
              _this.$message.error(res.data.message);
            }
          });
      },
      // 点击导出
      handleExport() {
        let _this = this;
        let placeIdArr = [];
        placeIdArr = placeIdArr.concat(_this.deptCheckedLeft);
        placeIdArr = placeIdArr.concat(_this.deptselectedLeft);
        if (this.deptCheckedLeft.join(",") == "") {
          this.$message.warning("请勾选部门或人员列表");
          return
        }
        this.spinning = true;
        let parameter ={
          current: _this.paginationRight.current,
          pageSize: _this.paginationRight.pageSize,
          userSerial: _this.userSerialCheckedLeft.join(","),
          deptSerial: placeIdArr.join(","),
          recordType: _this.defaultRecordType,
          searchVal: _this.searchNameRight
        };

          let jsonIn = encodeURI(encodeURI(JSON.stringify(parameter)));
        window.open(
          cfg.apiUrl + "api/user/face/exportUserFaceInfoList?jsonIn=" + jsonIn,
          "_self"
        );
        setTimeout(()=>{
          this.spinning = false;
        },1000)
      },
      // 选中授权表格
      onChangeRight(selectKeys,selectDatas) {
        console.log(selectKeys,selectDatas);
        this.selectedXhRight = selectKeys;
        this.selectedDatas = selectDatas;
      },
      // 行事件
      clickRow(record) {
        return {
          on: {
            // click: () => {
            //   // console.log("单击行: " + record)
            //   let keys = [];
            //   keys.push(record.userSerial);   //行数据一定要有唯一识别标志，否则无法选中，和表格的key一致
            //   this.selectedXhRight = keys;
            //   // console.log(this.selectedXhRight)
            // },
            dblclick: () => {
              // console.log("双击行: " + this.selectedXhRight);
              this.lookImg = cfg.apiUrl + record.photoPath;  //此处根据xh获取该人员的照片地址
              this.visibleImg = true;
            },
          }
        }
      },
      // 人脸删除
      faceDeletion(){
        let _this = this;
        let recordTypeArr = this.selectedDatas.filter(el=>{
          return el.userFace ==1
        });
        // console.log(recordTypeArr);
        if (this.selectedXhRight.length == 0) {
          this.$message.warning("请选择要删除人脸照片的人员");
        } else if(recordTypeArr.length > 0){
          this.$message.warning("包含未录人脸的人员，请重新选择");
        } else {
          this.$confirm({
            width: 500,
            okText: "确定",
            cancelText: "取消",
            title: "操作提示信息",
            content: h => '确定要删除选中的人脸照片吗?',
            onOk() {
              faceManage.deleteUserInfoAboutFace({
                userSerial: _this.selectedXhRight.join(",")
                }).then(res => {
                  if (res.data.success) {
                    _this.selectedXhRight = [];
                    _this.getPressUserQueryList();
                    _this.$message.success("删除成功!");
                  } else {
                    _this.$message.error(res.data.message);
                  }
                });
            },
            onCancel() {
            },
          });

        }
      },
      // 点击搜索
      handleQuery() {
        this.getPressUserQueryList();
      },
      handleChange(value) {
        // console.log(value);
        this.defaultRecordType = value;
      },
      popupScroll() {
      },

      // /** 导入模态框 */
      importData() {
        this.visibleImport = true;
      },
      //移除上传文件
      handleRemove(file) {
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },
      //上传之前判断文件类型
      beforeUpload(file) {
        // console.log(file);
        let fileName = file.name;
        let fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        // console.log(fileSuffix.toUpperCase())
        if (fileSuffix.toUpperCase() != ".ZIP") {
          this.fileList = [];
          this.$message.warning("请上传.zip格式文件");
        } else {
          if (this.fileList.length == 1) {
            this.fileList.splice(0, 1);
          }
          this.fileList = [...this.fileList, file];
        }
        return false;
      },
      //真正的导入
      handleOkImport(e) {
        let _this = this;
        const { fileList } = this;
        const formData = new FormData();
        if (fileList.length == 0) {
          this.$message.warning("请选择文件");
        } else {
          _this.unloadDisabled = true;
          fileList.forEach(file => {
            formData.append("file", file);
          });
          let hear = {
            // 'Access-Control-Allow-Credentials':'true', //解决session问题
            // "Access-Control-Allow-Origin":"*",
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //将表单数据传递转化为form-data类型
          };
          _this.confirmLoading = true;
          axios.post(cfg.apiUrl + "api/user/face/photo2",formData, {
            headers: hear
          })
            .then(function (response) {
              // console.log(response);
              if (response.data.success) {
                _this.fileList = [];
                _this.confirmLoading = false;
                _this.resultModel = true;    //打开导入成功的弹窗,展示成功多少，失败多少，以及去哪里查看
                _this.resultMsg = response.data.result;
                // _this.$message.success("导入成功");
                // _this.visibleImport = false;
                // _this.getPressUserQueryList();
              } else {
                _this.confirmLoading = false;
                _this.$message.error(response.data.message);
              }
              _this.unloadDisabled = false;
            })
            .catch(function (error) {
              _this.confirmLoading = false;
              _this.unloadDisabled = false;
              _this.$message.error("导入失败");
            });

        }
      },
      //关闭上传模态框
      handleCancelImport(e) {
        this.visibleImport = false;
        this.fileList = []
      },
      handleCancelImg(){
        this.visibleImg = false;
        this.lookImg = "";
      },
      handleCanResult(){
        this.resultModel = false;
        this.visibleImport = false;
        this.getPressUserQueryList();
      },




    }
  };
</script>

<style>

</style>
